package com.auto.qinglong.ui.screens

import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.auto.qinglong.ui.viewmodel.HomeViewModel
import com.auto.qinglong.ui.viewmodel.QlViewModel
import com.auto.qinglong.utils.QlDestinations
import com.auto.qinglong.utils.QlNavigationActions

/**
 * Created by YuanWei1 on 2025/6/12.
 *
 * Description:
 */
@Composable
fun QlScreen(widthSizeClass: WindowWidthSizeClass) {
    val viewModel: QlViewModel = hiltViewModel()
    val navController = rememberNavController()
//        全局跳转方法
    val navigationActions = remember(navController) {
        QlNavigationActions(navController)
    }
    //协程生命周期相关 代替 GlobalScope 或 lifecycleScope
    val coroutineScope = rememberCoroutineScope()
    //获取当前栈顶的NavBackStackEntry
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route ?: QlDestinations.HOME_ROUTE
    val isLoggedIn by viewModel.isLoggedIn.collectAsStateWithLifecycle()

    //未登录时进入登录页面
    LaunchedEffect(isLoggedIn) {
        if (isLoggedIn) {
            navController.navigate(QlDestinations.HOME_ROUTE) {
                popUpTo(QlDestinations.LOGIN) { inclusive = true }
            }
        } else {
            navController.navigate(QlDestinations.LOGIN) {
                popUpTo(QlDestinations.HOME_ROUTE) { inclusive = true }
            }
        }
    }

    NavHost(
        navController = navController,
        startDestination = QlDestinations.HOME_ROUTE,
    ) {
//            首页
        composable(route = QlDestinations.HOME_ROUTE) {
            val homeViewModel: HomeViewModel = hiltViewModel()
            HomeScreen(homeViewModel, navController, checkLog = {
                navController.navigate(QlDestinations.TASK_LOG + "/${it.key}")
            })
        }
//            登录页
        composable(route = QlDestinations.LOGIN) {
            LoginScreen(navController) {
                navController.navigate(QlDestinations.HOME_ROUTE) {
                    popUpTo(QlDestinations.LOGIN) {
                        inclusive = true
                    }
                }
            }
        }
//        任务日志
        composable(route = QlDestinations.TASK_LOG + "/{taskId}") {
            TaskLogScreen(navController, it.arguments?.getString("taskId")) {
                navController.popBackStack()
            }
        }
    }
}